package com.cloudeoffice.server.config.security;

import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtTokenUtil {
    private static final String CLAIM_KEY_USERNAME="sub";
    private static final String CLAIM_KEY_CREATED="created";
    @Value("${jwt.secret}")
    private String secret;
    @Value("${jwt.expiration}")
    private Long expiration;

    //根据用户消息能生成token
    public String generateToken(UserDetails userDetails){
        Map<String,Object> claims=new HashMap<>();
        claims.put(CLAIM_KEY_USERNAME,userDetails.getUsername());
        claims.put(CLAIM_KEY_CREATED,new Date());
        return generateToken(claims);
    }
    //从 token 中获取登入用户名
    public String getUserNameFromToken(String token){
        String username;
        try {
            Claims claims=getClaimsFromToken(token);
            username=claims.getSubject();
        } catch (Exception e) {
            username=null;
        }
        return username;
    }
    //判断 token 是否有效
    public boolean validateToken(String token,UserDetails userDetails){
        String username = getUserNameFromToken(token);
        return username.equals(userDetails.getUsername())&&!isTokenExpired(token);
    }
    //判断 token 是否可以被刷新
    public boolean canRefresh(String token){
        return !isTokenExpired(token);
    }
    //刷新 token
    public String refreshToken(String token){
        Claims claims = getClaimsFromToken(token);
        claims.put(CLAIM_KEY_CREATED,new Date());
        return generateToken(claims);
    }
    //判断 token 是否失效
    private boolean isTokenExpired(String token) {
        Date expireDate=getExpiredDateFromToken(token);
        return expireDate.before(new Date());
    }
    //从 token 中获取过期时间
    private Date getExpiredDateFromToken(String token) {
        Claims claimsFromToken = getClaimsFromToken(token);
        return claimsFromToken.getExpiration();
    }

    //从 token 中获取 载荷
    private Claims getClaimsFromToken(String token) {
        Claims claims=null;
        try {
            //
            claims=Jwts.parser()
                    //利用数字哈希解析
                    .setSigningKey(secret)
                    //解析 token
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return claims;
    }

    //根据载荷生成 JWT TOKEN
    private String generateToken(Map<String,Object> claims){
        return Jwts.builder()
                //设置载荷
                .setClaims(claims)
                //设置失效时间
                .setExpiration(generateExpirationDate())
                //设置签名哈希
                .signWith(SignatureAlgorithm.HS512,secret)
                .compact();
    }
    //生成token 失效时间
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis()+expiration*1000);
    }

}
